package camp.android.cookbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ActionBar.LayoutParams;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
//TODO: clean up data collection when finished
public class NewProcedure extends Activity{
	Recipe toCreate;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_procedure);

		toCreate = (Recipe) getIntent().getSerializableExtra("recipe");
		List<String> procedure = toCreate.getProcedureList();
		
		final LinearLayout outerLayout = (LinearLayout) findViewById(R.id.outer_layout_procedure);
		if(!procedure.isEmpty()) //add EditTexts for each stored procedure step (for editing)
		{
			EditText firstStep = (EditText) findViewById(R.id.first_step);
			firstStep.setText(procedure.get(0));
			
			for(int i = 1; i < procedure.size(); i++)
			{
				addStepInput(outerLayout, procedure.get(i));
			}
		}
		toCreate.clearProcedure(); //clear previously stored steps so that newly edited steps overwrite them
		
		EditText note = (EditText)findViewById(R.id.add_note);
		List<String> notes = toCreate.getNotesList();
		if(!notes.isEmpty()) //show previously created notes (for editing)
			note.setText(notes.get(0));
		toCreate.clearNotes(); //clear old notes so that only new notes show
		
		Button newStep = (Button) findViewById(R.id.add_another_step);
		newStep.setOnClickListener(new OnClickListener() { //adding another step to your directions
			@Override
			public void onClick(View v) { //add another ingredient by introducing new EditTexts before the plus button
				addStepInput(outerLayout, null);
			}
		});

		Button finishRecipe = (Button) findViewById(R.id.finish_new_recipe);

		finishRecipe.setOnClickListener(new OnClickListener() { //add all directions and notes to the recipe

			@Override
			public void onClick(View v) {
				String note = ((EditText) findViewById(R.id.add_note)).getText().toString();
				if (!note.equals(""))toCreate.addNote(note);

				for (int i = 1; i < outerLayout.getChildCount()-2; i++) {
					LinearLayout row = (LinearLayout)outerLayout.getChildAt(i);
					EditText step = (EditText)row.getChildAt(0);
					String nextDirection = step.getText().toString();
					if (nextDirection != null && !nextDirection.equals(""))
						toCreate.addStep(nextDirection);
				}


				//add recipe to database
				ArrayList<Recipe> ourRecipes = getRecipesFromFile();
				if (ourRecipes==null) ourRecipes = new ArrayList<Recipe>();
				if(ourRecipes.contains(toCreate))
					ourRecipes.remove(toCreate);
				ourRecipes.add(toCreate);
				//System.out.println("Just finished, and ourRecipes has " + ourRecipes.size() + ", and the last recipe is " + toCreate +", " + ourRecipes.get(5));
				writeRecipesToFile(ourRecipes);


				Intent i = new Intent(getApplicationContext(), RecipeView.class);
				i.putExtra("recipe", toCreate);
				startActivity(i);
			}
		});
	}

	final String STORAGE_FILE = "recipe_list";

	public void writeRecipesToFile(ArrayList<Recipe> toRecord) {
		File file = new File(getFilesDir(), "recipe_list");
		try {
			if (file.exists()) {
				file.delete();
			}
			file.createNewFile();
			ObjectOutputStream out = new ObjectOutputStream (new FileOutputStream(file));
			out.writeObject(toRecord);
			out.close();
		} catch (IOException e) {
			System.out.println(e + " an IOException in writeRecipes to File");
			e.printStackTrace();
		}
	}
	
	public ArrayList<Recipe> getRecipesFromFile() { //return the ArrayList<Recipe> representation of our internal storage
		try{
			if (new File(getFilesDir(), STORAGE_FILE).exists())    {//if we already have some recipes, load them into the arraylist
				ObjectInputStream in = new ObjectInputStream(openFileInput(STORAGE_FILE));
				ArrayList<Recipe> toReturn = (ArrayList<Recipe>) in.readObject();
				in.close();
				return toReturn;
			}
			else {
				File f = new File(getFilesDir(), STORAGE_FILE);
				f.createNewFile();
				return new ArrayList<Recipe>();
			}
		} catch (IOException e) { //might want to individualize to IOException and ClassNotFoundException
			e.printStackTrace();
			System.out.println(e + " an IOException in getRecipesFromFile");
			return null; //this probably bad practice
		} catch (ClassNotFoundException e) {
			System.out.println(e+ " a class Exception in getRecipesFromFile");
			return null;
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// app icon in Action Bar clicked; go home
			Intent intent = new Intent(this, RecipeListView.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	
	private LinearLayout addStepInput(LinearLayout layout, String defStep)
	{
		LinearLayout nextRow = new LinearLayout(getApplicationContext());
		EditText nextIngredient = new EditText(getApplicationContext());
		if(defStep == null)
			nextIngredient.setHint("Add another step...");
		else
			nextIngredient.setText(defStep);
		Button delete = new Button(getApplicationContext());
		delete.setText("X");
		delete.setOnClickListener(new DeleteOnClickListener());

		nextRow.addView(nextIngredient, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 1));
		nextRow.addView(delete, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 0));
		layout.addView(nextRow, layout.getChildCount()-2);
		return nextRow;
	}
}